package com.dhcc.android.base.db.Sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.dhcc.android.base.common.bean.User;

/**
 * 用户数据库管理类
 *
 * @author zhoudan
 * @date 2015年7月8日
 */
public class UserDBManager {

    private DBHelper helper;
    private SQLiteDatabase db;

    private String table = "User";

    public UserDBManager(Context context) {
        helper = new DBHelper(context);
        db = helper.getWritableDatabase();

        db.execSQL("CREATE TABLE IF NOT EXISTS User (userName VARCHAR PRIMARY KEY  NOT NULL , password VARCHAR);");
    }

    public void addUser(User user) {
        db.beginTransaction();
        try {
            String sql = "DELETE FROM " + table + " where userName = '" + user.getUserName() + "'";
            db.execSQL(sql);

            sql = "INSERT INTO " + table + " VALUES(?, ?)";
            db.execSQL(sql, new Object[]{user.getUserName(), user.getPassword()});

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        db.close();
    }

    public void addUser(String userName, String password) {
        db.beginTransaction();
        try {
            String sql = "DELETE FROM " + table + " where userName = '" + userName + "'";
            db.execSQL(sql);

            sql = "INSERT INTO " + table + " VALUES(?, ?)";
            db.execSQL(sql, new Object[]{userName, password});

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        db.close();
    }


    public User login(String userName, String password) {
        User u = null;

        String sql = "SELECT * FROM " + table + " where userName =? and password = ?";
        Cursor c = db.rawQuery(sql, new String[]{userName, password});
        System.out.println("###登录：" + userName + "----" + password);
        while (c.moveToNext()) {
            u = new User();
            u.setUserName(userName);
            u.setPassword(password);
        }
        c.close();
        db.close();
        return u;
    }

    public void addDefaultAccount(String userName, String password) {
        db.beginTransaction();
        try {
            String sql = "DELETE FROM " + table + " where userName = '" + userName + "'";
            db.execSQL(sql);
            System.out.println("sql:" + sql);
            sql = "INSERT INTO " + table + " VALUES(?, ?)";
            db.execSQL(sql, new Object[]{userName, password});
            System.out.println("sql:" + sql);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    /**
     * close database
     */
    public void closeDB() {
        if (db != null) {
            db.close();
        }
        System.out.println("--用户--数据库关闭-");
    }

}
